import crypto from '../utils/crypto';
import * as express from 'express';
import db from '../utils/db';
import http from '../utils/http';
import roomMgr from './roommgr';
import userMgr from './usermgr';
import tokenMgr from './tokenmgr';


//获取类型声明//
import configs_win from '../configs_win';
const GAME_SERVER_TYPE = configs_win.game_server();
type game_server_config = typeof GAME_SERVER_TYPE;
//获取类型声明//


export interface gameServerInfoType{
    id?;
    clientIp?;
    clientPort?;
    httpPort?;
    load?;
    ip?;
}



const app = express();
let config:game_server_config = null;
let serverIp = '';
let gameServerInfo:gameServerInfoType = null;
let lastTickTime = 0;



app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", '3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});



export default class Http_service{

    static start($config:game_server_config){

        config = $config;
        gameServerInfo = {
            id: config.SERVER_ID,
            clientIp: config.CLIENT_IP,
            clientPort: config.CLIENT_PORT,
            httpPort: config.HTTP_PORT,
            load: roomMgr.getTotalRooms(),
        };

        setInterval(update, 1000);
        app.listen(config.HTTP_PORT, config.FOR_ROOM_IP);
        console.log('游戏http服务器运行在：' + config.FOR_ROOM_IP + ':' + config.HTTP_PORT);
    }
}

/**
 * 向大厅服务器定时心跳
 */
function update(){
    if(lastTickTime + config.HTTP_TICK_TIME < Date.now()){
        lastTickTime = Date.now();
        gameServerInfo.load = roomMgr.getTotalRooms();
        http.get(config.HALL_IP, config.HALL_PORT, '/register_gs', gameServerInfo, (ret, data:ret) => {
            if(ret){
                if(data.errcode != 0){
                    console.log(data.errmsg);
                }
                if(data.ip != null){
                    serverIp = data.ip;
                }
            }
            else{
                lastTickTime = 0;
            }
        });
    }
}

//创建房间
app.get('/create_room', (req, res) => {

    const userId = parseInt(req.query.userid);
    const sign = req.query.sign;
    const gems = req.query.gems;
    let conf = req.query.conf;

    if(userId == null || sign == null || conf == null){
        http.send(res, 1, 'userId or sifn or conf is null');
        return;
    }
    
    const md5 = crypto.md5(userId + conf + gems + config.ROOM_PRI_KEY);
    if(md5 != req.query.sign){
        console.log('加密的用户信息无效');
        http.send(res, 1, 'sign验证没通过');
        return;
    }

    conf = JSON.parse(conf);
    roomMgr.createRoom(userId, conf, gems, serverIp, config.CLIENT_PORT, (errcode, roomId) => {
        if(errcode != 0 || roomId == null){
            http.send(res, errcode, '创建房间失败');
            return;
        }
        else{
            http.send(res, 0, 'Ok', {roomid: roomId});
        }
    });
    
});

//检查房间是否在运行中
app.get('/is_room_runing', (req, res) => {
    const roomId = req.query.roomid;
    const sign = req.query.sign;
    if(roomId == null || sign == null){
        http.send(res, 1, 'roomid或sign为空');
        return;
    }

    const md5 = crypto.md5(roomId + config.ROOM_PRI_KEY);
    if(md5 != sign){
        http.send(res, 2, 'sign验证失败');
        return;
    }

    http.send(res, 0, 'ok', {runing: true});
});


//进入房间
app.get('/enter_room', (req, res) => {
    const userId = parseInt(req.query.userid);
    const name = req.query.name;
    const roomId = req.query.roomid;
    const sign = req.query.sign;
    if(userId == null || roomId == null || sign == null){
        http.send(res, 1, 'userId或roomId或sign为空');
        return;
    }

    const md5 = crypto.md5(userId + name + roomId + config.ROOM_PRI_KEY);
    if(md5 != sign){
        http.send(res, 2, 'sign验证失败');
        return;
    }

    //安排玩家坐下
    roomMgr.enterRoom(roomId, userId, name, (ret) => {
        if(ret != 0){
            if(ret == 1){
                http.send(res, 4, '房间已经满了');
            }
            else if(ret == 2){
                http.send(res, 3, '没有找到房间');
            }
            return;
        }

        const token = tokenMgr.createToken(userId, 5000);
        http.send(res, 0, 'ok', {token: token});
    });
});


app.get('/get_server_info', (req, res) => {
    console.log(req);
});